<template>
  <view class="container">
    <!-- 顶部标题 -->
    <view class="title-container">
		<view style="width: 80px;height: 80px;border-radius: 8px;margin-bottom: 10px;">
			<img style="width: 100%;height: 100%;border-radius: 8px;" :src="logo" alt="" />
		</view>
      <text class="title">国酱通</text>
    </view>

    <!-- 表单容器 -->
    <view class="form-container">
      <!-- 登录按钮 -->
      <button class="login-btn" open-type="getWechatLogin" @click="getWechatLogin">快捷登录</button>
      <!-- 底部链接 -->
      <view class="footer-links flex-row justify-center" style="display: flex;align-items: center;font-size: 12px;">
		<radio style="transform:scale(0.8)" value="r1" :checked="false" /></label>
        <text class="link-text" style="font-size: 13px;">我已阅读并同意</text>
        <text class="divider-line" style="color: #409EFF;">《用户服务协议》《隐私政策》</text>
        <text class="link-text" style="color: #409EFF;"></text>
      </view>
    </view>
	<uni-popup ref="popup" type="bottom">
		<view style="height: 400rpx;background-color: #fff;border-top-right-radius: 10px;border-top-left-radius: 10px;padding: 20px 15px;">
			<view style="font-size: 16px;font-weight: bold;color: #333;line-height: 32px;">
				你当前还未获取手机号，是否获取？
			</view>
			<view style="font-size: 14px;font-weight: bold;color: #333;line-height: 28px;">
				用户隐私提示
			</view>
			<view style="font-size: 12px;line-height: 24px;color: #666;margin-bottom: 40px;">
				在您使用  国酱通  服务之前，如同意该服务对您的隐私保护指引，请点击“确认”开始使用本小程序
			</view>
			<view style="display: flex;justify-content: space-around;align-items: center;">
				<button 
				class="popup-button" style="background-color: #F2F2F2;color: #333;font-weight: 600;">取消</button>
				<button @getphonenumber="handlePhonenumber" open-type="getPhoneNumber" class="popup-button"
				 style="background-color: #409EFF;font-weight: 600;">确认</button>
				<!-- <button 
				class="popup-button"
				style="background-color: #2979ff;" open-type="getPhoneNumber" @="onGetPhoneNumber">确认授权</button> -->
			</view>
		</view>
	</uni-popup>
	<!-- <CustomPicker 
	     :visible="pickerVisible"
	      @change="onUserChange"
	      class="mt-40"
	    >
		<template #default="{ trigger }">
		  <view class="user-option">
		    当前还未授权手机号，是否授权手机号？
		  </view>
		</template>
	      <template #default="{ option }">
	        <view class="user-option">
	          <view class="user-info">
	            <text class="user-name">111</text>
	            <text class="user-desc">222</text>
	          </view>
	          <text class="iconfont icon-check"></text>
	        </view>
	      </template>
	    </CustomPicker> -->
  </view>
</template>
<script>
import loginApiWeiXin  from './login.js'
import {getWXphone}  from '../api/index.js'
import CustomPicker from '../../components/customPicker.vue';
export default {
	 components: {
	    CustomPicker
	  },
  data() {
    return {
		pickerVisible:true,
      phone: "",
      code: "",
      countdown: 0,
      timer: null,
      isLogging: false,
	  loginRes:{},
	  logo:require('../../static/logo_img.png'),
	  token:''
    };
  },
  computed: {
    // 验证表单是否有效
    isValid() {
      return /^1[3-9]\d{9}$/.test(this.phone) && /^\d{6}$/.test(this.code);
    },
  },
  onShow() {
	  // this.$refs.popup.open('bottom')
  },
  onLaunch() {
    this.initAuth();
	// this.loginByWechat()
  },
  mounted() {
  	this.loginByWechat()
  },
  methods: {
    loginByWechat() {
      // if (this.loginLoading) return;
      // 1. 获取code
      wx.login({
        provider: "weixin",
        success: (loginRes) => {
          console.log("获取code成功", loginRes.code);
		  this.loginRes = loginRes
		 
          // 2. 获取用户信息
          
        },
        fail: (err) => {
          console.error("获取code失败", err);
          uni.hideLoading();
          this.loginLoading = false;
          uni.showToast({
            title: "登录失败，请重试",
            icon: "none",
          });
        },
      });
    },
	getWechatLogin(){
		this.loginLoading = true;
		uni.showLoading({
		  title: "登录中...",
		  mask: true,
		});
		if(this.loginRes){
			uni.getUserProfile({
			  provider: "weixin",
			  desc: '用于完善用户资料',
			  success: (userRes) => {
			    console.log("获取用户信息成功", userRes.userInfo);
				uni.setStorage({
					key:'userInfo',
					data:JSON.stringify(userRes.userInfo)
				})
				
			    // 3. 发送code和用户信息到后端
			    this.sendLoginInfoToServer(this.loginRes.code, userRes.userInfo);
			  },
			  fail: (err) => {
			    console.error("获取用户信息失败", err);
			    uni.hideLoading();
			    this.loginLoading = false;
			
			    // 处理用户拒绝授权的情况
			    if (err.errMsg.includes("auth deny")) {
			      uni.showModal({
			        title: "提示",
			        content: "需要授权才能登录",
			        showCancel: false,
			        success: () => {
			          // 引导用户打开授权设置页
			          uni.openSetting();
			        },
			      });
			    } else {
			      uni.showToast({
			        title: "登录失败，请重试",
			        icon: "none",
			      });
			    }
			  },
			});
				
		}
		
	},
	//获取微信用户手机号
	onGetPhoneNumber(e){
		const { encryptedData, iv } = e.detail
		console.log('this.loginRes',e.detail.encryptedData)
		if(this.loginRes){
			this.getUserPhone(encryptedData, iv)
		}
	},
	handlePhonenumber(e) {
	   this.getUserPhone(this.token,e.detail.code)
	   },
	getUserPhone(token,code){
		const obj = {
			appPlatform:1,
			token:token,
			code:code
		}
		getWXphone(obj).then(res =>{
			if(res.code == 200){
				uni.setStorage({
					key:'phone',
					data:res.data.phoneNumber
				})
				uni.switchTab({url:'/pages/home/mine/index'})
			}
		})
		
	},

    // 发送登录信息到服务器
    async sendLoginInfoToServer(code, userInfo) {
		const res = await loginApiWeiXin({
			appPlatform:1,
			code:code
		})
		if(res.code == 200){
			uni.setStorage({
				key:'token',
				data:JSON.stringify(res.data.token)
			})
			this.token = res.data.token
			if(res.data.phoneNumber){
				uni.setStorage({
									key:'phone',
									data:res.data.phoneNumber
								})
				uni.switchTab({
							url:'/pages/home/mine/index'
						})
			}else{
				this.$refs.popup.open('bottom')
			}
			
			
		}
		
		return false
      uni.request({
        url: "/openApi/weChat/login",
        method: "POST",
        data: {
          code: code,
          userInfo: userInfo,
        },
        success: (res) => {
          console.log("登录API响应", res);

          if (res.data.code === 200) {
            // 登录成功，保存token和用户信息
            uni.setStorageSync("token", res.data.data.token);
            uni.setStorageSync("userInfo", res.data.data.userInfo);

            uni.hideLoading();
            this.loginLoading = false;

            // 跳转到首页
            uni.switchTab({
              url: "/pages/index/index",
            });
          } else {
            uni.hideLoading();
            this.loginLoading = false;
            uni.showToast({
              title: res.data.message || "登录失败，请重试",
              icon: "none",
            });
          }
        },
        fail: (err) => {
          console.error("登录API请求失败", err);
          uni.hideLoading();
          this.loginLoading = false;
          uni.showToast({
            title: "网络错误，请重试",
            icon: "none",
          });
        },
      });
    },

    // 登录
    login() {
      // 表单验证
      if (!this.isValid) {
        uni.showToast({
          title: "请填写正确的手机号和验证码",
          icon: "none",
        });
        return;
      }

      // 模拟登录
      console.log("用户登录:", {
        phone: this.phone,
        code: this.code,
      });

      uni.showLoading({
        title: "登录中...",
      });

      // 模拟登录请求延迟
      setTimeout(() => {
        uni.hideLoading();
        uni.showToast({
          title: "登录成功",
          icon: "success",
        });

        // 登录成功后跳转
        setTimeout(() => {
          uni.switchTab({
            url: "/pages/index/index",
          });
        }, 1000);
      }, 1500);
    },
  },

  // 页面销毁时清除定时器
  onUnload() {
    if (this.timer) {
      clearInterval(this.timer);
      this.timer = null;
    }
  },
};
</script>

<style scoped>
/* 引入字体图标 */
@font-face {
  font-family: "iconfont";
  src: url("https://at.alicdn.com/t/font_1788044_0dwu4guekcwr.ttf")
    format("truetype");
}

.container {
  height: 100vh;
  background: linear-gradient(to bottom, #e6f2ff, #ffffff);
  display: flex;
  flex-direction: column;
}

.title-container {
  margin-top: 150rpx;
  margin-bottom: 100rpx;
  text-align: center;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.title {
  font-size: 34rpx;
  font-weight: 500;
  color: #333333;
}

.subtitle {
  margin-top: 20rpx;
  font-size: 28rpx;
  color: #999999;
}

.form-container {
  flex: 1;
  padding: 0 30rpx;
}

.input-item {
  margin-bottom: 40rpx;
}

.input-label {
  display: block;
  margin-bottom: 10rpx;
  font-size: 28rpx;
  color: #666666;
}

input {
  width: 100%;
  height: 80rpx;
  font-size: 32rpx;
  border-bottom: 1rpx solid #eeeeee;
  padding: 0 10rpx;
  box-sizing: border-box;
}

.placeholder {
  color: #cccccc;
  font-size: 30rpx;
}

.get-code-btn {
  min-width: 200rpx;
  height: 80rpx;
  line-height: 80rpx;
  text-align: center;
  color: #1677ff;
  font-size: 28rpx;
  background-color: #e6f4ff;
  border-radius: 40rpx;
  padding: 0 20rpx;
}

.get-code-btn[disabled] {
  color: #999999;
  background-color: #f5f5f5;
}

.login-btn {
  margin-top: 60rpx;
  width: 100%;
  height: 90rpx;
  line-height: 90rpx;
  text-align: center;
  background-color: #409EFF;
  color: #ffffff;
  font-size: 30rpx;
  border-radius: 45rpx;
  border-color: #409EFF;
}

.login-btn[disabled] {
  background-color: #a8d2ff;
}

.login-methods {
  margin-top: 40rpx;
}

.method-btn {
  width: 80rpx;
  height: 80rpx;
  line-height: 80rpx;
  text-align: center;
  border-radius: 40rpx;
  background-color: #f5f5f5;
}

.iconfont {
  font-family: "iconfont" !important;
  font-size: 40rpx;
  font-style: normal;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

.icon-weixin {
  color: #07c160;
}

.icon-qq {
  color: #12b7f5;
}

.footer-links {
  margin-top: 60rpx;
  margin-bottom: 40rpx;
}

.link-text {
  color: #999999;
  font-size: 13px;
}

.divider-line {
  margin: 0 20rpx;
  color: #eeeeee;
  font-size: 13px;
}
.justify-center {
  display: flex;
  justify-content: center;
}
.popup-button{
	font-size: 12px;
	line-height: 70rpx;
	height: 70rpx;
	background-color: darkgrey;
	color: #fff;
	border: unset;
	border-width: 0;
	width: 150px;				
}
/* 去除默认边框 */
button::after {
  border: none;
}
</style>    